<template>
    <div class="p8-container">
        <div v-if="hasData" class="chart-container" :style="{width:width}">
            <h2>How the Fundraiser Communicated with Funders in Previous Production Stage</h2>
            <div class="chart-container">
                <div :class="className" :id="id" :style="{ height: height, width: width }"></div>
                <div class="x1-label" v-show="x1Show" @click="x1Show=false">
                    <div class="text-tip">
                        <span class="title">Backers’ Inquiries</span>: Backer’s number of
                        inquiries during the production stage:
                        <span
                                class="show-green"
                        >{{data1}}</span>, which is
                        <span class="show-green">71%</span> higher than platform average
                    </div>
                </div>
                <div class="x2-label" v-show="x2Show" @click="x2Show=false">
                    <div class="text-tip">
                        <span class="title">Update Frequency</span>
                        : Fundraiser’s update frequency during the production stage:
                        <span
                                class="show-red"
                        >{{parseFloat(data5).toFixed(1)}} days/post</span>, which is
                        <span class="show-red">12%</span> lower than platform average
                    </div>
                </div>
                <div class="x3-label" v-show="x3Show" @click="x3Show=false">

                    <div class="text-tip">
                        <span class="title">Number of Updates</span>
                        : Fundraiser posted
                        <span class="show-green">{{data4}}</span> updates during
                        the production stage, which is
                        <span class="show-green">56%</span> higher than platform average
                    </div>

                </div>
				
				
                <div class="x4-label" v-show="x4Show" @click="x4Show=false">

                    <div class="text-tip">
                        <span class="title">Sentiment of Backers’ Comments</span>
                        : Backers’ overall sentiment valence during the production stage:
                        <span
                                class="show-red"
                        >{{data3}}</span>, sentiment score ranges from 0
                        (extreme negative) to 1 (extreme positive)
                    </div>


                </div>
                <div class="x5-label" v-show="x5Show" @click="x5Show=false">

                    <div class="text-tip">
                        <span class="title">Fundraiser’s Replies to Backers’ Inquiries</span>
                        : Fundraiser’s reply ratio during the production stage:
                        <span
                                class="show-red"
                        >{{data2}}</span>, which is
                        <span class="show-red">12%</span>lower than platform average
                    </div>


                </div>
            </div>
        </div>
        <div v-else>
            <div class="no-data">
                The Fundraiser is New to the Platform
            </div>
        </div>
    </div>
</template>

<script>
    import echarts from "echarts";
    import {feature8Data} from "@/api/feature";
    import {mapState, mapMutations} from "vuex";

    export default {
        props: {
            className: {
                type: String,
                default: "chart"
            },
            id: {
                type: String,
                default: "chart"
            },
            width: {
                type: String,
                default: "200px"
            },
            height: {
                type: String,
                default: "200px"
            }
        },
        data() {
            return {
                chart: null,
                x5Show: false,
                x4Show: false,
                x3Show: false,
                x2Show: false,
                x1Show: false,
                hasData: true,
                showData: {},
                colorList: [],
                data1: 0,
                data2: 0,
                data3: 0,
                data4: 0,
                data5: 0
            };
        },
        watch: {
            canDraw(val) {
                if (val) {
                    this.initChart();
                }
            }
        },
        computed: {
            ...mapState({
                currentCampainId: state => state.campaign.currentCampainId,
                currentCampainCategory: state => state.campaign.currentCampainCategory,
                canDraw: state => state.campaign.canDraw
            })
        },
        mounted() {
            this.initChart();
            console.info("ddddd")
        },
        beforeDestroy() {
            if (!this.chart) {
                return;
            }
            this.chart.dispose();
            this.chart = null;
        },
        methods: {
            parseColor(hexStr) {
                return hexStr.length === 4
                    ? hexStr
                        .substr(1)
                        .split("")
                        .map(function (s) {
                            return 0x11 * parseInt(s, 16);
                        })
                    : [hexStr.substr(1, 2), hexStr.substr(3, 2), hexStr.substr(5, 2)].map(
                        function (s) {
                            return parseInt(s, 16);
                        }
                    );
            },

            // zero-pad 1 digit to 2
            pad(s) {
                return s.length === 1 ? "0" + s : s;
            },
            gradientColors(start, end, steps, gamma) {
                var i,
                    j,
                    ms,
                    me,
                    output = [],
                    so = [];
                gamma = gamma || 1;
                var normalize = function (channel) {
                    return Math.pow(channel / 255, gamma);
                };
                start = this.parseColor(start).map(normalize);
                end = this.parseColor(end).map(normalize);
                for (i = 0; i < steps; i++) {
                    ms = i / (steps - 1);
                    me = 1 - ms;
                    for (j = 0; j < 3; j++) {
                        so[j] = this.pad(
                            Math.round(
                                Math.pow(start[j] * me + end[j] * ms, 1 / gamma) * 255
                            ).toString(16)
                        );
                    }
                    output.push("#" + so.join(""));
                }
                return output;
            },
            async initChart() {
                try {
                    var that = this;

                    this.chart = echarts.init(document.getElementById(this.id));

                    var featureServerData = await feature8Data();

                    featureServerData.forEach((item, index) => {
                        if (item["campaign_id"] == this.currentCampainId) {
                            this.showData = item;
                        }
                    });

                    var element = this.showData

                    if (JSON.stringify(element) == '{}') {
                        this.hasData = false;
                        return;
                    }

                    if (0 == element["contrast_num_comments"] && 0 == element["contrast_num_update"]
                        && 0 == element["contrast_reply_ratio"] && 0 == element["contrast_update_freq"]
                        && 0 == element["sentiment"]) {
                        this.hasData = false;
                        return;

                    }

                    // num_comments reply_ratio sentiment num_update update_freq

                    this.data1 = element['num_comments']
                    this.data2 = element['reply_ratio']
                    this.data3 = element['sentiment']
                    this.data4 = element['num_update']
                    this.data5 = element['update_freq']


                    if (that.showData["num_historical_campaigns"] > 1) {
                        this.colorList = this.gradientColors(
                            "#FFFF00",
                            "#FF0000",
                            that.showData["num_historical_campaigns"]
                        );
                    } else {
                        this.colorList.push("#FF0000");
                    }

                    // featureServerData.forEach(element => {
                    //   console.log(element)
                    // });

                    let option = {
                        tooltip: {
                            trigger: "item",
                            backgroundColor: "rgba(0,0,250,0.2)",
                            formatter: function (params) {
                                console.log(params)
                                console.log("*****")

                                var result = ""

                                result += "Number of Backers' Inquiries: " + that.data1 + "</br>"
                                result += "Fundraiser's Reply Ratio: " + that.data2 + "</br>"
                                result += "Sentiment of Comments: " + that.data3 + "</br>"
                                result += "Number of Updates: " + that.data4 + "</br>"
                                result += "Update Frequency (days): " + parseFloat(that.data5).toFixed(1)


                                return result
                            }
                        },
                        /*legend: {
                                      type: 'scroll',
                                      bottom: 10,
                                      data: (function (){
                                          var list = [];
                                          for (var i = 1; i <=6; i++) {
                                              list.push(i + 2000 + '');
                                          }
                                          return list;
                                      })()
                                  },*/
                        // visualMap: {
                        //   top: "middle",
                        //   right: 10,
                        //   color: ["red", "yellow"],
                        //   calculable: true
                        // },
                        radar: {
                            indicator: [
                                {text: "Number of Backers' Inquiries", max: 1},
                                {text: "Fundraiser's Reply Ratio", max: 1},
                                {text: "Sentiment of Comments", max: 1},
                                {text: "Number of Updates", max: 1},
                                {text: "Update Frequency (days)", max: 1}
                            ],
                            name: {
                                textStyle: {color: 'black'}
                            },

                            triggerEvent: true
                        },
                        series: (function () {
                            var series = [];

                            var data = [];
                            var element = that.showData;

                            // contrast_num_comments   contrast_update_freq contrast_num_update sentiment contrast_reply_ratio


                            data.push(element["contrast_num_comments"]).toFixed(3);
                            data.push(element["contrast_reply_ratio"]);
                            data.push(element["sentiment"]).toFixed(3);
                            data.push(element["contrast_num_update"]).toFixed(3);
                            data.push(element["contrast_update_freq"]).toFixed(3);


                            // var data1 = element[]

                            series.push({
                                type: "radar",
                                symbol: "none",
                                itemStyle: {
                                    normal: {
                                        areaStyle: {type: "default"},
                                        color: "#7dc1ff"
                                    }
                                },
                                label: {
                                    color: "black"
                                },
                                areaStyle: {
                                    normal: {
                                        width: 1,
                                        opacity: 0.62,
                                        color: "#a0d3ff" // 选择区域颜色
                                    }
                                },
                                lineStyle: {
                                    color: "#7dc1ff"
                                },
                                // itemStyle: {
                                //   normal: {
                                //     lineStyle: {
                                //       width: 1,
                                //       color: color
                                //     }
                                //   }
                                // },
                                data: [
                                    {
                                        value: data,
                                    }
                                ]
                            });
                            return series;
                        })()
                    };

                    this.chart.setOption(option);

                    this.chart.on("click", params => {
                        console.log(params.name);

                        if ("Number of Backers' Inquiries" == params.name) {
                            this.x1Show = true;
                        } else if ("Fundraiser's Reply Ratio" == params.name) {
                            this.x5Show = true;
                        } else if ("Sentiment of Comments" == params.name) {
                            this.x4Show = true;
                        } else if ("Number of Updates" == params.name) {
                            this.x3Show = true;
                        } else if ("Update Frequency (days)" == params.name) {
                            this.x2Show = true;
                        }
                    });
                } catch (error) {
                    this.hasData = false;
                    console.log(error);
                    console.error("feature8 init error");
                }
            }
        }
    };
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
    .p8-container {
        text-align: center;
        h2 {
            text-align: center;
            margin-bottom: 26px;
        }
        .chart-container {
            position: relative;
            .x1-label {
                position: absolute;
                top: 6px;
                right: 160px;
                /*word-break: break-all;*/
            }
            .x2-label {
                position: absolute;
                top: 160px;
                left: 460px;
                /*word-break: break-all;*/
            }
            .x3-label {
                position: absolute;
                top: 270px;
                right: 10px;
                /*word-break: break-all;*/
            }
            .x4-label {
                position: absolute;
                top: 270px;
                left: 10px;
                /*word-break: break-all;*/
            }
            .x5-label {
                position: absolute;
                top: 30px;
                left: 30px;
                /*word-break: break-all;*/
            }
            .text-tip {
                /*word-wrap: break-word;*/
                /*word-break: break-all;*/
				text-align:left;
                width: 226px;
                border: solid 1px gray;
                padding: 6px;
                background: white;
                z-index: 999;
            }
            .title {
                font-weight: bold;
            }

            .show-green {
                color: green;
            }
            .show-red {
                color: red;
            }
        }
    }
</style>
